import { DirectiveBinding } from "vue";
import { useAuthStore } from "@/stores/modules/auth";

const checkPermission = (el: HTMLElement, binding: DirectiveBinding) => {
  const { value } = binding;
  const authStore = useAuthStore();
  const authButtons = authStore.authButtonListGet || [];

  if (value && value instanceof Array && value.length > 0) {
    const permissionFlag = value;

    const hasPermission = authButtons.some((btn: string) => {
      return permissionFlag.includes(btn) || btn === "*:*:*";
    });

    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el);
    }
  } else {
    throw new Error(`need roles! Like v-permission="['admin:user:add']"`);
  }
};

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  }
};
